<?php
class Bliss_Steam
{
	const KEY = 'C02079C2B8DCF01C639F2F655B2591C5';
	const URL = 'http://api.steampowered.com';

	protected $interface;
	protected $method;
	protected $version = 'v0001';
	protected $params;

	public function __construct()
	{

	}

	/**
	 * Sets the command interface
	 *
	 * @param string $interface
	 */
	public function setInterface($interface)
	{
		$this->interface = $interface;
	}

	/**
	 * Sets the command method
	 *
	 * @param string $method
	 */
	public function setMethod($method)
	{
		$this->method = $method;
	}

	/**
	 * Sets the command version
	 *
	 * @param string $version
	 */
	public function setVersion($version)
	{
		$this->version = (substr($version, 0, 1) == 'v') ? $version : "v{$version}";
	}

	/**
	 * Adds additional parameters to the request
	 *
	 * @param array $params
	 */
	public function setParams(array $params)
	{
		$this->params = $params;
	}

	/**
	 * Quick way to set the command
	 * <interface>/<method>/<version>
	 *
	 * @param string $command
	 * @param array $params
	 */
	public function setCommand($command=null, array $params=null)
	{
		$command = isset($command) ? explode('/', trim($command, '/')) : array();
		if(isset($command[0])) $this->setInterface($command[0]);
		if(isset($command[1])) $this->setMethod($command[1]);
		if(isset($command[2])) $this->setVersion($command[2]);

		$this->params  = $params;
	}

	/**
	 * Creates the request URL
	 *
	 * @return string
	 */
	protected function buildUrl()
	{
		if(!isset($this->interface, $this->method, $this->version)) {
			throw new Exception("Interface, method and version must be provided.");
		}
		$params = isset($this->params) ? http_build_query($this->params) : null;
		$url = self::URL."/{$this->interface}/{$this->method}/{$this->version}/?key=".self::KEY."&{$params}";
		return $url;
	}

	/**
	 * Executes the command and returns the results.
	 * The command and parameters can be passed directly .
	 *
	 * @param string $command
	 * @param array $params
	 * @return string
	 */
	public function execute($command=null, array $params=null)
	{
		if(isset($command)) {
			$this->setCommand($command, $params);
		}

		$curl = curl_init($this->buildUrl());
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

		$result = curl_exec($curl);
		curl_close($curl);
		return $result;
	}
}
